package jnpf.base.service.impl;


import jnpf.base.service.DbSyncService;
import jnpf.base.service.DbTableService;
import jnpf.base.service.DblinkService;
import jnpf.database.entity.DbLinkEntity;
import jnpf.database.model.DbFieldMod;
import jnpf.database.sql.SqlBase;
import jnpf.database.util.ConnUtil;
import jnpf.database.util.DbTypeUtil;
import jnpf.database.util.JdbcOriginUtil;
import jnpf.database.util.JdbcUtil;
import jnpf.exception.DataException;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.util.List;

/**
 * 数据同步
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2019年9月27日 上午9:18
 */
@Slf4j
@Service
public class DbSyncServiceImpl implements DbSyncService {

    @Autowired
    private DblinkService dblinkService;
    @Autowired
    private DbTableService dbTableService;

    @Override
    public Integer checkExecute(String dbLinkIdFrom, String dbLinkIdTo, String table) throws Exception {
        DbLinkEntity linkFrom = dblinkService.getInfo(dbLinkIdFrom);
        DbLinkEntity linkTo = dblinkService.getInfo(dbLinkIdTo);
        //验证一（同库）
        if (dbLinkIdFrom.equals(dbLinkIdTo) ||
                (linkFrom.getHost() + linkFrom.getPort() + linkFrom.getDbName())
                        .equals(linkTo.getHost() + linkTo.getPort() + linkTo.getDbName())) {
            return -1;
        }
        @Cleanup Connection connFrom = ConnUtil.getConn(linkFrom);
        @Cleanup Connection connTo = ConnUtil.getConn(linkTo);
        //验证二（表存在）
        if (dbTableService.getList(linkTo.getId()).stream().filter(tableOne ->
                tableOne.getTable().equals(table)).count() == 0) {
            // 被同步表不存在
            return 2;
        } else {
            //验证三（验证表数据）
            String toSql = "SELECT count(*) AS F_COUNT FROM " + table;
            if (JdbcUtil.queryOneInt(connTo, toSql, "F_COUNT") > 0) {
                //被同步表存在数据
                return 3;
            }
        }
        syncTable(connFrom, connTo, table);
        return 0;
    }

    @Override
    public void executeImport(String dbLinkIdFrom, String dbLinkIdTo, String table) throws Exception {
        @Cleanup Connection connFrom = ConnUtil.getConn(dblinkService.getInfo(dbLinkIdFrom));
        @Cleanup Connection connTo = ConnUtil.getConn(dblinkService.getInfo(dbLinkIdTo));
        SqlBase sqlBase = DbTypeUtil.getDb(connTo).getSqlBase();
        //删除To表
        JdbcUtil.creUpDe(connTo, sqlBase.getDeleteSql(table));
        //获取建表语句
        String createTableSql = sqlBase.getCreateSql(table,
                JdbcOriginUtil.getDbTableInfoModel(connFrom, table).getComment(),
                JdbcOriginUtil.getConnFieldModList(connFrom, table));
        JdbcUtil.creUpDe(connTo, createTableSql);
        //同步数据
        syncTable(connFrom, connTo, table);
    }

    private void syncTable(Connection connFrom, Connection connTo, String table) throws DataException {
        //初始库Form
        String fromSql = "SELECT * FROM " + table;
        List<List<DbFieldMod>> dataList = JdbcUtil.queryIncludeFieldMods(connFrom, fromSql);
        if (dataList.size() > 0){
            //被同步库同步To
            String sqlData = DbTypeUtil.getDb(connTo).getSqlBase().batchInsertSql(dataList, table);
            JdbcUtil.creUpDe(connTo, sqlData);
        }
    }


}
